#!/usr/bin/perl
##
## postinstall for LenovoUTIL.pkg
##
## Copyright (C) 2011 - 2012 Lenovo (Beijing) Limited
## Copyright (C) 2009 - 2012 Brother Industries, LTD.

##### Library ########################################################
use File::Temp qw/ tempfile tempdir /;
use Foundation;
use File::Path;
require "$ARGV[0]/Contents/Resources/BRUtility.pm";

##### Grabal ########################################################
my $EXIT_VALUE 		= 0;


##### Main ########################################################
my $PKG_LOCATION = $ARGV[0];
my $TMP_DIR 	 = tempdir(TMPDIR => 1, CLEANUP => 1);
&postflightMain();
0;

##### Functions ########################################################
#
# @function		removeLastPathComponent
# @abstruct		Remove the last path component from the path. 
# @args[0]		The path you want to remove the last path component.
# @result		The path which is removed the last path component.
#
sub removeLastPathComponent()
{
	my $retVal;
	my $this_func_name = ( caller 0 )[3];
	my $srcPath = $_[0];
	my $find;
	
	$find = rindex($srcPath, "/");
	if( $find < 0 )
	{
		$retVal = $srcPath;
		print STDERR $this_func_name.": Last path: no matched.\n";
	}
	else
	{
		$retVal = substr($srcPath, 0, $find);
	}
	
	return $retVal;
}


#
# Main
#
sub postflightMain
{
	my $this_func_name = ( caller 0 )[3];	
	my $pkgDirectory = &removeLastPathComponent($PKG_LOCATION);
	my $version = BRUtilityGetOSMajorVersion();

	my $installDestination = "/Library/Printers/Lenovo/Utilities";
	my $originalUtilitiesDir = "/Library/Printers/Brother/Utilities";
	my $twainPkg = $pkgDirectory."/LenovoTWAIN.pkg";
	my $rspPkg = $pkgDirectory."/LenovoRSP.pkg";
	
	# Create application alias (TWAIN)
	if( -d "$twainPkg" )
	{
		system("sudo ln -s '$originalUtilitiesDir'/ControlCenter/ControlCenter.app '$installDestination'/ControlCenter");
		system("sudo ln -s '$originalUtilitiesDir'/DeviceSelector/DeviceSelector.app '$installDestination'/DeviceSelector");
	}
	
	# Create application alias (RSP)
	if( -d "$rspPkg" )
	{
		system("sudo ln -s '$originalUtilitiesDir'/RemoteSetup.app '$installDestination'/RemoteSetup");
	}
	
	
	# Open Install Utility
	if( $version == "5" )
	{	## Only Mac OS X 10.5(M-PC09-271) execute the commnad with current user (not root).
		my $currentUser = $ENV{'USER'};
		my $utilApp = $pkgDirectory."/InstallUtility.app";
		if( !$currentUser )
		{
			print STDERR $this_func_name."(): Invalid user\n";
		}
		else
		{
			if( -e "$utilApp" )
			{
				my $launchCommand = "open '$utilApp'";
				system("su -l $currentUser -c \"$launchCommand\"");
			}
		}
	}
	else
	{
		my $utilApp = $pkgDirectory."/InstallUtility.app";
		if( -e "$utilApp" )
		{
			my $launchCommand = "open '$utilApp'";
			system($launchCommand);
		}
	}
	
}

